package com.byd.android.VideoPlayer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.byd.android.agreement.InstructionList;
import com.byd.android.agreement.message.Video;
import com.byd.android.mediaplayer.BaseActivity;
import com.byd.android.mediaplayer.MediaService;
import com.byd.android.mediaplayer.R;
import com.byd.android.start.MainInterface;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static com.byd.android.agreement.InstructionList.MODE.MODE_VIDEO;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_BACK;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_CONTINUE;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_NEXT;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_PAUSE;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_PLAY;
import static com.byd.android.agreement.InstructionList.ORDER.ORDER_PREVIOUS;

public class VideoPlayer extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "VideoPlayer";
    public VideoPlayer instance = null;
    public MediaService.MediaBinder mediaBinder;
    ListView mVideoListView;  //视频列表
    VideoAdapter mVideoAdapter;   //适配器
    List<Video> videoList = new ArrayList<>();
    int videoSize;
    private ViewPager viewPager;  //对应的viewPager
    private List<View> viewList;//view数组
    private SurfaceView surfaceView;
    private MediaPlayer player = new MediaPlayer();
    private int currentMusicIndex = 0;  //索引
    private TextView mCurTime, mTime;    //进度条时间
    private SeekBar mSeekBar;
    private LinearLayout mLayout;
    VideoPlayer.MyHandler mHandler = new MyHandler(VideoPlayer.this);
    VideoPlayer.CountTimeThread countTimeThread;
    private int mCount;
    String mPath;
    int position;
    int mDuration;

    Handler handler = new Handler() {
    };

    @Override
    protected void sendHandlerToService() {
        mServiceBinder.sendHandler(mHandler);
        mServiceBinder.getMode(MODE_VIDEO);
    //    mServiceBinder.sendVideoList(videoList);
        Log.d("VideoPlayer", "sendHandlerToService: videoPlayer is Binder ");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewpager);   //viewpager
        initView();

//        Intent intent = new Intent(VideoPlayer.this, MediaService.class);
//        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_playpause:  //暂停 播放
                PlayPause();
                break;
            case R.id.btn_pre:
                Previous();
                break;
            case R.id.btn_next:
                Next();
                break;
            case R.id.video:
                if (mLayout.isShown()) {
                    mLayout.setVisibility(View.GONE);
                } else {
                    mLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.back:
                Intent i = new Intent(VideoPlayer.this, MainInterface.class);
                startActivity(i);
                break;
            default:
                break;
        }
    }

    /**
     * 视频界面初始化
     */
    void initView() {
        viewPager = findViewById(R.id.viewpager);
        LayoutInflater inflater = getLayoutInflater();
        View videolist = inflater.inflate(R.layout.video_list, null);  //视频列表界面
        View videoplayer = inflater.inflate(R.layout.video_playface, null);
        viewList = new ArrayList<>();// 将要分页显示的View装入数组中
        viewList.add(videoplayer);
        viewList.add(videolist);
        PagerAdapter pagerAdapter = new PagerAdapter() {

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                // TODO Auto-generated method stub
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return viewList.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                // TODO Auto-generated method stub
                container.removeView(viewList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                // TODO Auto-generated method stub
                container.addView(viewList.get(position));


                return viewList.get(position);
            }
        };
        viewPager.setAdapter(pagerAdapter);
        instance = this;
        AbstructProvider provider = new VideoProvider(instance);
        videoList = provider.getList();

        //视频初始化

        Log.d("VideoPlayer", "initView: videoList is " + videoList.get(2).getVideoName());
        //发送video列表给服务

        videoSize = videoList.size();
        surfaceView = videoplayer.findViewById(R.id.video);
        mVideoAdapter = new VideoAdapter(this, videoList);
        mVideoListView = videolist.findViewById(R.id.videolist);
        mVideoListView.setAdapter(mVideoAdapter);

        //点击视频列表播放
        mVideoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                currentMusicIndex = position;
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                initVideoPlayer(currentMusicIndex);

            }
        });
        loadImages();
        mCurTime = videoplayer.findViewById(R.id.tv_curtime);  //进度条起始时间
        mTime = videoplayer.findViewById(R.id.tv_time);   //进度条终止时间
        mCurTime.setText("00:00:00");
        mTime.setText("00:00:00");
        mCount = videoList.size();   //列表长度
        Button mPre = videoplayer.findViewById(R.id.btn_pre);  //上一首按键
        Button mPlayPause = videoplayer.findViewById(R.id.btn_playpause);  //播放暂停按键
        Button mNext = videoplayer.findViewById(R.id.btn_next);  //下一首按键
        mLayout = videoplayer.findViewById(R.id.btn_bar);   //进度条布局
        mPre.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mPlayPause.setOnClickListener(this);
        surfaceView.setOnClickListener(this);
        mSeekBar = videoplayer.findViewById(R.id.progress); //进度条
        VideoPlayer.SeekBarListener mListener = new SeekBarListener();
        mSeekBar.setOnSeekBarChangeListener(mListener);
        mSeekBar.setEnabled(false);//seekbar初始化时时不可拖动的
        AutoPlay();  //自动播放
        handler.postDelayed(runnable, 1000);
        startCountTimeThread();//这是自动隐藏控件的线程

        //返回键
        Button mBack = findViewById(R.id.back);
        mBack.setOnClickListener(this);
    }

    //进度条运行
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                if (player.isPlaying()) {//当处于播放状态时
                    if (!mSeekBar.isEnabled()) {//当seekbar不可用时
                        mSeekBar.setEnabled(true);//seekbar可用
                    }
                    position = player.getCurrentPosition();
                    String curtime = VideoProvider.millions2hour(position);
                    String time = VideoProvider.millions2hour(mDuration);
                    mTime.setText(time);
                    mCurTime.setText(curtime);
                    mSeekBar.setProgress(position);
                    mSeekBar.setMax(mDuration);
                }
                handler.postDelayed(this, 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 视频缩略图
     */
    private void loadImages() {
        final Object data = getLastNonConfigurationInstance();
        if (data == null) {
            new LoadImagesFromSDCard().execute();
        } else {
            final LoadedImage[] photos = (LoadedImage[]) data;
            if (photos.length == 0) {
                new LoadImagesFromSDCard().execute();
            }
            for (LoadedImage photo : photos) {
                addImage(photo);
            }
        }
    }

    private void addImage(LoadedImage... value) {
        for (LoadedImage image : value) {
            mVideoAdapter.addPhoto(image);
            mVideoAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        final ListView grid = mVideoListView;
        final int count = grid.getChildCount();
        final LoadedImage[] list = new LoadedImage[count];

        for (int i = 0; i < count; i++) {
            final ImageView v = (ImageView) grid.getChildAt(i);
            list[i] = new LoadedImage(
                    ((BitmapDrawable) v.getDrawable()).getBitmap());
        }

        return list;
    }

    /**
     * 获取视频缩略图
     *
     * @param videoPath
     * @param width
     * @param height
     * @param kind
     * @return
     */
    private Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
        Bitmap bitmap;
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
        @Override
        protected Object doInBackground(Object... params) {
            Bitmap bitmap;
            for (int i = 0; i < videoSize; i++) {
                bitmap = getVideoThumbnail(videoList.get(i).getData(), 120, 120, MediaStore.Images.Thumbnails.MINI_KIND);
                if (bitmap != null) {
                    publishProgress(new LoadedImage(bitmap));

                }
            }
            return null;
        }

        @Override
        public void onProgressUpdate(LoadedImage... value) {
            addImage(value);
        }
    }


    /**
     * 视频播放
     */


    //视频播放函数
    private void initVideoPlayer(int Index) {
        try {
            player.reset();
            mPath = videoList.get(Index).getData();
            mDuration = (int) videoList.get(Index).getDuration();
            player.setDataSource(mPath);
            SurfaceHolder holder = surfaceView.getHolder();
            player.setDisplay(holder);
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //自动播放下一首
    private void AutoPlay() {
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (currentMusicIndex < mCount - 1) {
                    currentMusicIndex = currentMusicIndex + 1;
                    initVideoPlayer(currentMusicIndex);
                    player.start();
                } else {
                    currentMusicIndex = 0;
                    initVideoPlayer(0);
                    player.start();
                }

            }
        });
    }

    //播放暂停函数
    private void PlayPause() {
        if (!player.isPlaying()) {
            if (position != 0) {//当播放时间不为0
                initVideoPlayer(currentMusicIndex);
                player.seekTo(position);//跳转到之前的播放时间
            } else {
                initVideoPlayer(currentMusicIndex);
            }
        } else {
            player.pause();
            mSeekBar.setEnabled(false);
        }
    }
    private void continuePlay(){
        player.start();
    }
    private void pause(){
        player.pause();
    }


    //上一个函数
    private void Previous() {
        if (currentMusicIndex == 0) {
            currentMusicIndex = mCount - 1;
            initVideoPlayer(currentMusicIndex);
        } else {
            currentMusicIndex = currentMusicIndex - 1;
            initVideoPlayer(currentMusicIndex);
        }
    }

    //下一个函数
    private void Next() {
        if (currentMusicIndex == mCount - 1) {
            currentMusicIndex = 0;
            initVideoPlayer(0);
        } else {
            currentMusicIndex = currentMusicIndex + 1;
            initVideoPlayer(currentMusicIndex);
        }
    }

    public class SeekBarListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            if (fromUser == true && player.isPlaying()) {
                //fromUser判断是否为用户自己操作
                player.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        countTimeThread.reset();// 重置时间
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            boolean isVisible = mLayout.isShown();
            if (!isVisible) {
                mLayout.setVisibility(View.VISIBLE);
                return true;
            }
        }
        return super.onTouchEvent(event);
    }

    private void startCountTimeThread() {
        countTimeThread = new CountTimeThread(5);
        countTimeThread.start();
    }

    /**
     * 隐藏需要隐藏的布局
     */
    private void hide() {
        if (mLayout.isShown()) {
            //mLayout.isShown()判断控件是否在VISIBIL状态
            mLayout.setVisibility(View.GONE);
        }
    }

    /**
     * Handler消息传递机制
     */
    class MyHandler extends Handler {
        // 发送消息的id
        private final int MSG_HIDE = 0x901;
        // WeakReference垃圾回收机制
        private WeakReference<VideoPlayer> weakRef;

        public MyHandler(VideoPlayer videoPlayer) {
            weakRef = new WeakReference<>(videoPlayer);
        }

        @Override
        public void handleMessage(Message msg) {
            final VideoPlayer videoPlayer = weakRef.get();

            if (videoPlayer != null) {
                switch (msg.what) {
                    case MSG_HIDE:
                        hide();
                        break;
                    case ORDER_PLAY:
                        currentMusicIndex = msg.arg1;
                        initVideoPlayer(currentMusicIndex);

                        break;
                    case ORDER_CONTINUE:
                        continuePlay();
                        break;
                    case ORDER_PAUSE:
                        Log.d(TAG, "handleMessage: order is pause/play");
                        pause();
                        break;
                    case ORDER_NEXT:
                        Log.d(TAG, "handleMessage: order is next");
                        Next();
                        break;
                    case ORDER_PREVIOUS:
                        Log.d(TAG, "handleMessage: order is previous");
                        Previous();
                        break;
                    case ORDER_BACK:
                        mServiceBinder.stop(/* reset */ true);
                        onBackPressed();
                        break;
                    case MODE_VIDEO:
                       // mediaBinder.sendVideoList(videoList);

                        break;

                    default:
                        break;

                }
            }
        }

        /**
         * 发送消息
         */
        public void sendHideControllMessage() {
            obtainMessage(MSG_HIDE).sendToTarget();
        }

    }

    public class CountTimeThread extends Thread {
        private final long maxVisibleTime;
        private long startVisibleTime;

        /**
         * 设置控件显示时间 second单位是秒
         *
         * @param second
         */
        public CountTimeThread(int second) {
            maxVisibleTime = second * 1000;// 换算为毫秒
            setDaemon(true);// 设置为后台进程
        }

        /**
         * 如果用户有操作，则重新开始计时隐藏时间
         */
        public synchronized void reset() {
            startVisibleTime = System.currentTimeMillis();
        }

        @Override
        public void run() {
            startVisibleTime = System.currentTimeMillis();// 初始化开始时间

            while (true) {
                // 如果时间达到最大时间，则发送隐藏消息
                if (startVisibleTime + maxVisibleTime < System.currentTimeMillis()) {
                    mHandler.sendHideControllMessage();

                    startVisibleTime = System.currentTimeMillis();
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {

                }
            }
        }
    }

    protected void onStop() {

        super.onStop();
        player.stop();
        player.release();
    }

    protected void onDestroy() {

        super.onDestroy();
    }

}
